<template>
  <div class="box">
    <div class="title">登录</div>
    <a-form :model="formState" name="normal_login" class="login-form" @finish="onFinish" size="large" :rules="rules">
      <a-form-item name="username">
        <a-input v-model:value="formState.username" placeholder="账号">
          <template #prefix>
            <UserOutlined />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item name="password">
        <a-input-password v-model:value="formState.password" placeholder="密码">
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" class="submit_btn">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import {
  UserOutlined,
  LockOutlined,
  GithubFilled,
  WechatFilled,
  AlipayCircleFilled,
  TaobaoCircleFilled,
  WeiboCircleFilled
} from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import md5 from 'md5-node';
import { login,getUserInfo } from '@/apis/admin/login';
import {useUserInfo} from '@/store/useUserInfo'

export default {
  components: {
    UserOutlined,
    LockOutlined,
    GithubFilled,
    WechatFilled,
    AlipayCircleFilled,
    TaobaoCircleFilled,
    WeiboCircleFilled
  },
  emits: ['changeForm'],
  setup(props, { emit }) {
    const router = useRouter();

    const user = useUserInfo()

    const formState = ref({
      username: '',
      password: ''
    });

    // 登录提交
    const onFinish = async () => {
      const sendFormData = {
        username: formState.value.username,
        password: md5(formState.value.password)
      };
      try {
        const res = await login(sendFormData);
        if (res.code === 0) {
          sessionStorage.setItem('token', res.data.token);
          const userInfo = await getUserInfo();
          user.setUserInfo(userInfo.data);
          // 不是管理员则不能进入
          if(!userInfo.data.isAdmin){
             user.setUserInfo({});
             sessionStorage.setItem('token', '');
             message.error('请使用管理员账号登录');
             return;
          }
          if(userInfo.data.isBan){
            user.setUserInfo({});
             sessionStorage.setItem('token', '');
             message.error('该用户已被禁用!');
             return;
          }
          message.success('登录成功！');
          router.push('/admin/user');
        } else {
          message.error(res.message);
        }
      } catch (error) {
        message.error('登录失败');
      }
    };

    // 密码验证函数
    const validatePsd = (value) => {
      const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,12}$/;
      return reg.test(value);
    };

    // 表单验证规则
    const rules = {
      username: [{
        required: true,
        message: '请输入你的账号！',
      }],
      password: [
        { required: true, message: '请输入密码' },
        {
          validator: (_, value) => {
            if (!validatePsd(value)) {
              return Promise.reject('密码6-12位由数字和字母组成');
            }
            return Promise.resolve();
          }
        }
      ]
    };

    return {
      formState,
      onFinish,
      rules,
      changeForm: (type) => emit('changeForm', type)
    };
  }
};
</script>

<style lang="less" scoped>
.box {
  padding: 40px 36px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 0 8px #ddd;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.title {
  padding-bottom: 10px;
  font-weight: 700;
  font-size: 26px;
}



.submit_btn {
  width: 100%;
}
</style>